﻿using AutoMapper;
using MediatR;
using Medical.Api.Write.Application.Command.RecyclingCleaning;
using Medical.Domain.Enum;
using Medical.Domain.RecoveryCleaning;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Medical.Api.Write.Application.Handler.RecyclingCleaning
{
    /// <summary>
    /// 添加登记清洗命令处理
    /// </summary>
    public class AddCleaningRegistrationCommandHandlter : IRequestHandler<AddCleaningRegistrationCommand, ApiResult<int>>
    {
        /// <summary>
        /// 清洗仓储
        /// </summary>
        private readonly IBaseRepository<CleaningRegistration> cleaningRegistrationRep;

        /// <summary>
        /// 回收仓储
        /// </summary>
        private readonly IBaseRepository<InstrumentRecovery> instrumentRecoveryRep;

        /// <summary>
        /// automapper
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="cleaningRegistrationRep">清洗仓储</param>
        /// <param name="instrumentRecoveryRep">回收仓储</param>
        /// <param name="mapper">automapper</param>
        public AddCleaningRegistrationCommandHandlter(
            IBaseRepository<CleaningRegistration> cleaningRegistrationRep,
            IBaseRepository<InstrumentRecovery> instrumentRecoveryRep,
            IMapper mapper)
        {
            this.cleaningRegistrationRep = cleaningRegistrationRep;
            this.instrumentRecoveryRep = instrumentRecoveryRep;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddCleaningRegistrationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 1. 验证物品ID是否存在并且状态为已回收
                if (request.ItemIds == null || !request.ItemIds.Any())
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Data = 0,
                        Msg = "请选择需要清洗的物品"
                    };
                }

                var recoveryItems = instrumentRecoveryRep.GetAll()
                    .Where(x => request.ItemIds.Contains(x.Id))
                    .ToList();

                // 确认所有ID都存在
                if (recoveryItems.Count != request.ItemIds.Count)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Data = 0,
                        Msg = "选择的物品中包含不存在的物品ID"
                    };
                }

                // 确认所有物品都是已回收状态
                var invalidItems = recoveryItems.Where(x => x.Status != RecoveryStatusEnum.已回收).ToList();
                if (invalidItems.Any())
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Data = 0,
                        Msg = $"选择的物品中包含非已回收状态的物品，请检查"
                    };
                }

                // 2. 创建清洗登记记录
                var cleaningRegistration = mapper.Map<CleaningRegistration>(request);

                // 默认设置清洗结果为合格
                cleaningRegistration.CleaningResult = true;
                //清洗时长
                cleaningRegistration.CleaningDuration = 0;
                //完成时间
                cleaningRegistration.FinishTime = DateTime.Now;
                cleaningRegistration.FinishPerson = "";
                cleaningRegistration.CleaningState = RecoveryStatusEnum.待清洗;
                // 添加清洗记录
                cleaningRegistrationRep.Create(cleaningRegistration);

                // 3. 更新物品状态为已清洗
                foreach (var item in recoveryItems)
                {
                    item.Status = RecoveryStatusEnum.已清洗;
                    instrumentRecoveryRep.Update(item);
                }

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Data = cleaningRegistration.Id,
                    Msg = "登记清洗成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Data = 0,
                    Msg = ex.Message,
                };
            }
        }
    }
}
